import {
  createRouter,
  createWebHashHistory,
  createWebHistory
} from 'vue-router'
import { Router, RouteRecordRaw } from 'vue-router'
import { loadEnv } from '@build/index'
import { getModulesRouter, whiteListRouter } from './routes'
import {
  filterTree,
  ascending,
  formatFlatteningRoutes,
  formatTwoStageRoutes
} from './menus'
import { buildHierarchyTree } from '@/utils/tree'
import { AppRouteRecordRaw, HistoryModeEnum } from './types'
import { ref } from 'vue'

// for rendering menus
export const constantRoutes = formatTwoStageRoutes(
  formatFlatteningRoutes(buildHierarchyTree(ascending(getModulesRouter())))
).concat(whiteListRouter)

export const menus = ref<AppRouteRecordRaw[]>(filterTree(ascending(getModulesRouter())))

const historyMode =
  loadEnv().VITE_ROUTER_HISTORY === HistoryModeEnum.HASH
    ? createWebHashHistory()
    : createWebHistory()

const router = createRouter({
  // Create history
  history: historyMode,
  // Create Routes
  routes: constantRoutes as unknown as RouteRecordRaw[],
  // Whether trailing slashes should be disallowed. Default is false
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

export function rebuildMenu(records: AppRouteRecordRaw[]): void {
  menus.value = filterTree(ascending(records))
}

export default router